package com.xky.ui.module.salesManagement;

import com.xky.pojo.SalesShipments;
import com.xky.ui.module.salesManagement.select.SelectSalesShipment;
import com.xky.ui.module.salesManagement.add.AddSalesShipment;
import com.xky.ui.module.salesManagement.delete.DeleteSalesShipment;
import com.xky.ui.module.salesManagement.select.AdvancedSearchSalesShipmentDialog;
import com.xky.ui.module.salesManagement.update.UpdateSalesShipment;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xky.ui.main.MainView.autoRefreshTimer;
import static com.xky.ui.main.MainView.updateStatusMessage;

/**
 * 销售发货管理界面类
 */
public class SalesShipmentsManagement {

    // 表格组件
    private static JTable table;
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color ADD_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color UPDATE_BUTTON_COLOR = new Color(52, 152, 219);
    private static final Color DELETE_BUTTON_COLOR = new Color(231, 76, 60);
    private static final Color SEARCH_BUTTON_COLOR = new Color(52, 73, 94);
    private static final Color REFRESH_BUTTON_COLOR = new Color(142, 68, 173);
    private static final Color SEPARATOR_COLOR = new Color(0, 191, 255);
    private static final Color HIGHLIGHT_ROW_COLOR = new Color(235, 245, 251);
    private static final Color ALTERNATE_ROW_COLOR = new Color(248, 251, 255);
    
    // 定义字体常量
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 26);
    private static final Font SUBTITLE_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font TABLE_HEADER_FONT = new Font("微软雅黑", Font.BOLD, 15);
    private static final Font TABLE_CELL_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    
    // 状态颜色映射
    private static final Map<String, Color> STATUS_COLORS = new HashMap<>();

    static {
        STATUS_COLORS.put("待发货", new Color(230, 126, 34));
        STATUS_COLORS.put("已发货", new Color(41, 128, 185));
        STATUS_COLORS.put("运输中", new Color(46, 204, 113));
        STATUS_COLORS.put("已签收", new Color(39, 174, 96));
        STATUS_COLORS.put("已取消", new Color(231, 76, 60));
    }
    
    // 状态代码到显示文本的映射
    private static final Map<String, String> STATUS_MAP = new HashMap<>();

    static {
        STATUS_MAP.put("pending", "待发货");
        STATUS_MAP.put("shipped", "已发货");
        STATUS_MAP.put("in_transit", "运输中");
        STATUS_MAP.put("delivered", "已签收");
        STATUS_MAP.put("cancelled", "已取消");
    }
    
    // 日期时间格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 创建销售发货信息面板
     *
     * @param refreshAction 刷新操作
     * @return 销售发货信息面板
     */
    public static JPanel createShipmentsPanel(Runnable refreshAction) {
        JPanel panel = new JPanel(new BorderLayout(10, 10)) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                // 创建渐变背景 - 从浅蓝色到白色
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(255, 255, 255));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        panel.setBorder(new EmptyBorder(15, 15, 15, 15));

        // 创建顶部面板（标题和按钮）
        JPanel topPanel = new JPanel(new BorderLayout(0, 10));
        topPanel.setOpaque(false);
        
        // 标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel("销售发货管理");
        titleLabel.setFont(TITLE_FONT);
        titleLabel.setForeground(PRIMARY_COLOR);
        titleLabel.setBorder(new EmptyBorder(0, 10, 0, 0));
        
        JLabel subtitleLabel = new JLabel("管理和查询所有销售发货信息");
        subtitleLabel.setFont(SUBTITLE_FONT);
        subtitleLabel.setForeground(Color.GRAY);
        subtitleLabel.setBorder(new EmptyBorder(0, 12, 5, 0));
        
        JPanel labelsPanel = new JPanel(new BorderLayout());
        labelsPanel.setOpaque(false);
        labelsPanel.add(titleLabel, BorderLayout.NORTH);
        labelsPanel.add(subtitleLabel, BorderLayout.CENTER);
        
        titlePanel.add(labelsPanel, BorderLayout.WEST);
        
        // 分割线
        JSeparator separator = new JSeparator();
        separator.setForeground(SEPARATOR_COLOR);
        separator.setBackground(SEPARATOR_COLOR);
        
        // 操作按钮面板
        JPanel buttonPanel = createButtonPanel(refreshAction);
        
        // 添加到顶部面板
        topPanel.add(titlePanel, BorderLayout.NORTH);
        topPanel.add(separator, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 创建表格和滚动面板
        JScrollPane scrollPane = createShipmentsTable();
        
        // 给表格添加圆角边框
        scrollPane.setBorder(BorderFactory.createCompoundBorder(
            new EmptyBorder(5, 0, 5, 0),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(SEPARATOR_COLOR, 1, true),
                BorderFactory.createEmptyBorder(8, 8, 8, 8)
            )
        ));
        
        // 状态面板
        JPanel statusPanel = new JPanel(new BorderLayout());
        statusPanel.setOpaque(false);
        statusPanel.setBorder(new EmptyBorder(5, 0, 0, 0));

        // 添加到主面板
        panel.add(topPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(statusPanel, BorderLayout.SOUTH);

        return panel;
    }


    /**
     * 创建按钮面板
     *
     * @param refreshAction 刷新操作
     * @return 按钮面板
     */
    private static JPanel createButtonPanel(Runnable refreshAction) {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 10));
        buttonPanel.setOpaque(false);

        // 创建按钮
        JButton addButton = createStyledButton("添加发货", ADD_BUTTON_COLOR);
        JButton updateButton = createStyledButton("修改发货", UPDATE_BUTTON_COLOR);
        JButton deleteButton = createStyledButton("删除发货", DELETE_BUTTON_COLOR);
        JButton queryButton = createStyledButton("高级查询", SEARCH_BUTTON_COLOR);
        JButton refreshButton = createStyledButton("刷新数据", REFRESH_BUTTON_COLOR);

        // 设置按钮大小更一致
        Dimension buttonSize = new Dimension(110, 35);
        addButton.setPreferredSize(buttonSize);
        updateButton.setPreferredSize(buttonSize);
        deleteButton.setPreferredSize(buttonSize);
        queryButton.setPreferredSize(buttonSize);
        refreshButton.setPreferredSize(buttonSize);

        // 按钮事件
        addButton.addActionListener(e -> {
            new AddSalesShipment();
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        updateButton.addActionListener(e -> {
            if (table.getSelectedRow() != -1) {
                int selectedRow = table.getSelectedRow();
                if (table.getRowSorter() != null) {
                    selectedRow = table.getRowSorter().convertRowIndexToModel(selectedRow);
                }
                int shipmentId = (int) table.getModel().getValueAt(selectedRow, 0);
                new UpdateSalesShipment(shipmentId);
            } else {
                new UpdateSalesShipment();
            }
            
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        deleteButton.addActionListener(e -> {
            if (table.getSelectedRow() != -1) {
                int selectedRow = table.getSelectedRow();
                if (table.getRowSorter() != null) {
                    selectedRow = table.getRowSorter().convertRowIndexToModel(selectedRow);
                }
                int shipmentId = (int) table.getModel().getValueAt(selectedRow, 0);
                new DeleteSalesShipment(shipmentId);
            } else {
                new DeleteSalesShipment();
            }
            
            if (refreshAction != null) {
                refreshAction.run();
            }
        });

        queryButton.addActionListener(e -> {
            Window window = SwingUtilities.getWindowAncestor((Component) e.getSource());
            AdvancedSearchSalesShipmentDialog dialog = new AdvancedSearchSalesShipmentDialog(window, table);
            dialog.setVisible(true);
            
            if (dialog.isConfirmed() && refreshAction != null) {
                refreshAction.run();
                updateStatusMessage("已执行高级查询");
            }
        });

        refreshButton.addActionListener(e -> {
            SelectSalesShipment.resetSearchStatus();
            if (refreshAction != null) {
                refreshAction.run();
                updateStatusMessage("销售发货数据已刷新");
                
                // 启动自动刷新
                if (autoRefreshTimer != null && !autoRefreshTimer.isRunning()) {
                    autoRefreshTimer.start();
                }
            }
        });

        // 添加按钮到面板
        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(refreshButton);

        return buttonPanel;
    }
    
    /**
     * 创建样式化按钮
     *
     * @param text    按钮文本
     * @param bgColor 背景颜色
     * @return 按钮对象
     */
    private static JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(BUTTON_FONT);
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        
        // 设置按钮圆角
        button.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        button.setMargin(new Insets(5, 10, 5, 10));
        
        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(brightenColor(bgColor, 0.1f));
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(bgColor);
            }
        });
        
        return button;
    }
    
    /**
     * 调亮颜色
     *
     * @param color  原始颜色
     * @param factor 调亮因子
     * @return 调亮后的颜色
     */
    private static Color brightenColor(Color color, float factor) {
        int r = Math.min(255, (int) (color.getRed() * (1 + factor)));
        int g = Math.min(255, (int) (color.getGreen() * (1 + factor)));
        int b = Math.min(255, (int) (color.getBlue() * (1 + factor)));
        return new Color(r, g, b);
    }

    /**
     * 创建销售发货表格
     *
     * @return 包含表格的滚动面板
     */
    public static JScrollPane createShipmentsTable() {
        // 表格列名
        String[] columnNames = {"发货单ID", "发货单号", "关联订单ID", "仓库ID", "发货日期", 
                               "承运商", "物流单号", "运输方式", "状态", "备注", 
                               "创建时间", "更新时间"};

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置表格不可编辑
            }
            
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex == 0 || columnIndex == 2 || columnIndex == 3) {
                    return Integer.class; // ID列使用整数类型
                }
                return String.class;
            }
        };

        // 创建表格
        table = new JTable(model);
        table.setRowHeight(35);
        table.setFont(TABLE_CELL_FONT);
        table.getTableHeader().setFont(TABLE_HEADER_FONT);
        table.getTableHeader().setBackground(PRIMARY_COLOR);
        table.getTableHeader().setForeground(Color.BLACK);
        table.getTableHeader().setOpaque(true);
        table.getTableHeader().setReorderingAllowed(false); // 禁止拖动列
        table.getTableHeader().setResizingAllowed(true); // 允许调整列宽
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setShowGrid(true);
        table.setGridColor(new Color(230, 230, 230));
        table.setFillsViewportHeight(true);
        
        // 设置表格自动调整大小模式
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        
        // 设置交替行颜色
        table.setDefaultRenderer(Object.class, new TableCellRenderer() {
            private final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();
            
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, 
                    boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(
                        table, value, isSelected, hasFocus, row, column);
                
                if (c instanceof JLabel) {
                    JLabel label = (JLabel) c;
                    label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
                    
                    // 居中显示
                    if (column != 9) { // 备注列除外
                        label.setHorizontalAlignment(JLabel.CENTER);
                    }

                    // 设置行背景颜色
                    if (isSelected) {
                        c.setBackground(HIGHLIGHT_ROW_COLOR);
                        c.setForeground(PRIMARY_COLOR);
                    } else {
                        c.setBackground(row % 2 == 0 ? Color.WHITE : ALTERNATE_ROW_COLOR);
                        c.setForeground(Color.BLACK);
                    }
                    
                    // 设置状态的显示样式
                    if (column == 8 && value != null) { // 状态列
                        String status = value.toString();
                        if (STATUS_COLORS.containsKey(status)) {
                            label.setForeground(Color.WHITE);
                            label.setBackground(STATUS_COLORS.get(status));
                            label.setOpaque(true);
                            label.setBorder(BorderFactory.createEmptyBorder(2, 8, 2, 8));
                            label.setHorizontalAlignment(JLabel.CENTER);
                        }
                    }
                }
                
                return c;
            }
        });
        
        // 设置表格列宽
        int[] columnWidths = {70, 100, 70, 70, 100, 100, 100, 100, 100, 200, 150, 150};
        for (int i = 0; i < Math.min(columnWidths.length, table.getColumnModel().getColumnCount()); i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(columnWidths[i]);
        }
        
        // 添加双击打开编辑功能
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int selectedRow = table.getSelectedRow();
                    if (selectedRow != -1) {
                        if (table.getRowSorter() != null) {
                            selectedRow = table.getRowSorter().convertRowIndexToModel(selectedRow);
                        }
                        int shipmentId = (int) table.getModel().getValueAt(selectedRow, 0);
                        new UpdateSalesShipment(shipmentId);
                    }
                }
            }
        });

        
        // 设置表格排序
        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(model);
        table.setRowSorter(sorter);

        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        
        return scrollPane;
    }

    
    /**
     * 更新表格数据
     *
     * @param table         表格组件
     * @param shipmentsList 销售发货列表
     */
    public static void updateTableData(JTable table, List<SalesShipments> shipmentsList) {
        if (table == null) return;
        
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);

        for (SalesShipments shipment : shipmentsList) {
            // 获取状态的显示文本
            String statusDisplay = STATUS_MAP.getOrDefault(shipment.getStatus(), shipment.getStatus());
            
            Object[] rowData = {
                shipment.getShipmentId(),
                shipment.getShipmentNumber(),
                shipment.getOrderId(),
                shipment.getWarehouseId(),
                shipment.getShipmentDate() != null ? shipment.getShipmentDate().format(DATE_FORMATTER) : "",
                shipment.getCarrier(),
                shipment.getTrackingNumber(),
                shipment.getShippingMethod(),
                statusDisplay,
                shipment.getNotes(),
                shipment.getCreatedTime() != null ? shipment.getCreatedTime().format(DATETIME_FORMATTER) : "",
                shipment.getUpdatedTime() != null ? shipment.getUpdatedTime().format(DATETIME_FORMATTER) : ""
            };
            model.addRow(rowData);
        }
        
        // 更新状态栏信息
        Component parent = table.getParent();
        while (parent != null && !(parent instanceof JPanel)) {
            parent = parent.getParent();
        }
        
        if (parent != null) {
            Component[] components = parent.getParent().getComponents();
            for (Component component : components) {
                if (component instanceof JPanel && ((JPanel) component).getComponentCount() > 0) {
                    Component c = ((JPanel) component).getComponent(0);
                    if (c instanceof JLabel) {
                        JLabel statusLabel = (JLabel) c;
                        break;
                    }
                }
            }
        }
    }
}




